<? session_start();
include 'constants.php'; 
include 'functions.php';


$error_msg;
if($_POST){
	$action = $_POST['action'];
	$db=new SQLiteDatabase("db/mandi");
	$employee_number = sanitize(urldecode($_POST['employee_number']));
	$sold = sanitize(urldecode($_POST['sold']));
	

	if($action == 'view'){
		$query = "SELECT * FROM sale_table WHERE employee_number = ".
			$employee_number." AND sold_timestamp = ".$sold;
		
		
		if($result = $db->query($query, $error_msg)){
			//success! erase POST variables so a new entry can be made
			$row=$result->fetch(SQLITE_ASSOC);
		} else {
			//write error message further down in doc
		}
	} else {
		//action = edit
		$_POST['departed_timestamp'] = ($_POST['departed_timestamp']) ? ($_POST['departed_timestamp']) : 'null' ;
		
		$query = "UPDATE sale_table SET ".
			"market_name = \"".sanitize($_POST['market_name'])."\"".
			", departed_timestamp = ".$_POST['departed_timestamp'].
			", entry_id = \"".$_POST['entry_id']."\"".
			", toll_number = ".$_POST['toll_number'].
			", seller_license = ".$_POST['seller_license'].
			", buyer_license = ".$_POST['buyer_license'].
			", produce_id = ".$_POST['produce_id'].
			", weight = ".$_POST['weight'].
			", rate_per_quintal = ".$_POST['rate_per_quintal'].
			", total_sale = ".$_POST['total_sale'].
			", fees_unload = ".$_POST['fees_unload'].
			", fees_clean = ".$_POST['fees_clean'].
			", fees_weigh = ".$_POST['fees_weigh'].
			", fees_load = ".$_POST['fees_load'].
			", fees_stitch = ".$_POST['fees_stitch'].
			", fees_pack = ".$_POST['fees_pack'].
			", commissions_comm_agent = ".$_POST['commissions_comm_agent'].
			", commissions_mandi = ".$_POST['commissions_mandi'].
			" WHERE employee_number = ".$_POST['employee_number']." AND".
			" sold_timestamp = ".$_POST['sold_timestamp'];

		if(@$db->queryExec($query, $error_msg)){
			//success! erase POST variables so a new entry can be made
			$success_msg = 'Data edited successfully. <a href="'.BASE_URL.'edit">New Form</a>';
			
			$row = array();
			foreach($_POST as $key=>$value){
				$row[$key] = $value;
			}
		} else {
			//write error message further down in doc
		}
	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Mandi Form Edit</title>
</head>

<body>
<?
include 'navbar.php'; ?>
<div class="body-content">
<h2>Edit Sale Form</h2>
<?
echo '<p>';
if($success_msg){ echo $success_msg; }
if($error_msg){ echo $error_msg; }
echo '</p>';

//var_dump($_POST);
//var_dump($row);

if($row){ ?>
	<form action="" method="POST" id="entry_form">
		<p>Market Name: <input id="market_name" type="text" name="market_name" value="<?=$row['market_name']?>"></input></p>
		<p>Supervising Employee ID: <input type="text" name="employee_number" value="<?=$row['employee_number']?>"></input></p>
		<p>Sold: <input type="text" name="sold_timestamp" value="<?=$row['sold_timestamp']?>"></input></p>
		<p>Departed: <input type="text" name="departed_timestamp" value="<?=$row['departed_timestamp']?>"></input></p>
		<p>Entry ID: <input type="text" name="entry_id" value="<?=$row['entry_id']?>"></input></p>
		<p>Toll Number: <input type="text" name="toll_number" value="<?=$row['toll_number']?>"></input></p>
		<p>Seller License: <input id="seller_license" type="text" name="seller_license" value="<?=$row['seller_license']?>"></input></p>
		<p>Buyer License: <input id="buyer_license" type="text" name="buyer_license" value="<?=$row['buyer_license']?>"></input></p>
		<div id="myAutoComplete">
			<p>Produce: <input type="text" name="input_product_name" id="input_product_name" value=""></input>
				<input type="hidden" name="produce_id" id="produce_id" value="<?=$row['produce_id']?>"></input></p>
			<div id="myContainer" style="display:none;"></div>
		</div>
		<p>Weight (Quintals): <input type="text" name="weight" value="<?=$row['weight']?>"></input></p>
		<p>Rate (Rupees per Quintal): <input type="text" name="rate_per_quintal" value="<?=$row['rate_per_quintal']?>"></input></p>
		<p>Total Sale: <input type="text" name="total_sale" value="<?=$row['total_sale']?>"></input></p>
		<h2>Fees (Rupees)</h2>
		<p>Unload: <input type="text" name="fees_unload" value="<?=$row['fees_unload']?>"></input></p>
		<p>Clean: <input type="text" name="fees_clean" value="<?=$row['fees_clean']?>"></input></p>
		<p>Weigh: <input type="text" name="fees_weigh" value="<?=$row['fees_weigh']?>"></input></p>
		<p>Load: <input type="text" name="fees_load" value="<?=$row['fees_load']?>"></input></p>
		<p>Stitch: <input type="text" name="fees_stitch" value="<?=$row['fees_stitch']?>"></input></p>
		<p>Pack: <input type="text" name="fees_pack" value="<?=$row['fees_pack']?>"></input></p>
		<h2>Commissions (Rupees):</h2>
		<p>Commission Agent: <input type="text" name="commissions_comm_agent" value="<?=$row['commissions_comm_agent']?>"></input></p>
		<p>Mandi: <input type="text" name="commissions_mandi" value="<?=$row['commissions_mandi']?>"></input></p>
		<input type="hidden" name="action" value="edit"></input>
		<p><input type="submit"></input></p>
	</form>
<? } else {
	?>
	<form action="" method="POST">
		<p>Enter Sale Supervisor ID: <input type="text" name="employee_number" value="<?=$_POST['employee_number']?>"></input></p>
		<p>Enter timestamp of sale: <input type="text" name="sold" value="<?=$_POST['sale']?>"></input></p>
		<input type="hidden" name="action" value="view"></input>
		<p><input type="submit"></input></p>
	</form>
	<?
}
?>

<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/event/event-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/dom/dom-min.js"></script>

<!-- Autocomplete -->
<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.9.0/build/autocomplete/assets/skins/sam/autocomplete.css">
<script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/datasource/datasource-min.js"></script>
<script src="http://yui.yahooapis.com/2.9.0/build/autocomplete/autocomplete-min.js"></script>

<script type="text/javascript">
function IsNumeric(input){
   return (input - 0) == input && input.length > 0;
}

var YU = YAHOO.util;

var sellerToggle = function (e){
	var value = e.target.value;
	if(value != '' && IsNumeric(value)){
		var url = '<?=BASE_URL?>webservice?action=license&type=seller&id='+value;
		var callback = {
			success: function(o) {
				var results = YAHOO.lang.JSON.parse(o.responseText);
				
				var name = YU.Dom.get('bearer-name');
				var addr = YU.Dom.get('bearer-addr');
				var wrapper = YU.Dom.get('bearer-details');
				
				if(!wrapper){
					var name = document.createElement('div');
						YU.Dom.addClass(name, 'name');
						name.id = 'bearer-name';
					var addr = document.createElement('div');
						YU.Dom.addClass(addr, 'addr');
						addr.id = 'bearer-addr';
					var wrapper = document.createElement('div');
						YU.Dom.addClass(wrapper, 'bearer-details details');
						wrapper.id = 'bearer-details';
				}
				
				name.innerHTML = results['name'];
				addr.innerHTML = results['addr_street']+' '+
					results['addr_state']+' '+results['addr_pincode'];
				wrapper.appendChild(name);
				wrapper.appendChild(addr);
				YU.Dom.insertAfter(wrapper, YU.Dom.get('seller_license'));
				//YU.Dom.get('input_org').value = results['organization_name'];
			}
		};
		YU.Connect.asyncRequest('GET', url, callback);
	}
};

function buyerToggle(e){
	var value = e.target.value;
	if(value != '' && IsNumeric(value)){
		var url = '<?=BASE_URL?>webservice?action=license&type=buyer&id='+value;
		var callback = {
			success: function(o) {
				var results = YAHOO.lang.JSON.parse(o.responseText);
				
				var name = YU.Dom.get('commagent-name');
				var addr = YU.Dom.get('commagent-addr');
				var wrapper = YU.Dom.get('commagent-details');
				
				if(!wrapper){
					var name = document.createElement('div');
						YU.Dom.addClass(name, 'name');
						name.id = 'commagent-name';
					var addr = document.createElement('div');
						YU.Dom.addClass(addr, 'addr');
						addr.id = 'commagent-addr';
					var wrapper = document.createElement('div');
						YU.Dom.addClass(wrapper, 'commagent-details details');
						wrapper.id = 'commagent-details';
				}
				
				name.innerHTML = results['name'];
				addr.innerHTML = results['addr_street']+' '+
					results['addr_state']+' '+results['addr_pincode'];
				wrapper.appendChild(name);
				wrapper.appendChild(addr);
				YU.Dom.insertAfter(wrapper, YU.Dom.get('buyer_license'));
				//YU.Dom.get('input_org').value = results['organization_name'];
			}
		};
		YU.Connect.asyncRequest('GET', url, callback);
	}
};

YU.Event.addListener('seller_license', 'focusout', sellerToggle);
YU.Event.addListener('buyer_license', 'focusout', buyerToggle);

var products;
var productsCallback = {
	success: function(o) {
		products = YAHOO.lang.JSON.parse(o.responseText);
			var v = YU.Dom.get('produce_id');
			if(v){
				v = v.value;
			}

		var product_keys = [];
		for(var key in products){
			product_keys.push(key);
			if(v && products[key] == v){
				YU.Dom.get('input_product_name').value = key;
			}
		}

		var oDS = new YAHOO.util.LocalDataSource(products);
		var myAutoComp = new YAHOO.widget.AutoComplete("input_product_name","myContainer", new YAHOO.util.LocalDataSource(product_keys));
		myAutoComp.typeAhead = true;
		myAutoComp.typeAheadDelay = 0;
		myAutoComp.queryDelay = 0;
	}
};
var pUrl = '<?=BASE_URL?>'+'webservice?action=getproducts';
YU.Connect.asyncRequest('GET', pUrl, productsCallback);

YU.Event.addListener('input_product_name', 'focusout', function (e){
	var value = e.target.value;
	if(value != ''){
		YU.Dom.get('produce_id').value = products[value];
	}
});

if(YU.Dom.get('entry_form')){
	YU.Dom.get('seller_license').focus();
	YU.Dom.get('buyer_license').focus();
	YU.Dom.get('market_name').focus();
}

</script>
</div>
</body></html>